/**
 * @description: OSS工具类
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */
import { OSSService } from '@midwayjs/oss';
import { basename } from 'path';
import { Provide, Inject } from '@midwayjs/core';
import fs = require('fs');

@Provide()
export class OSSUtils {

  @Inject()
  ossService: OSSService;

  /** 
   * @description: 单文件上传
   * @param {string} filePath 文件路径
   * @param {*} dest osscdn目录，文件上传地址的目录
   * @param {*} unlink 是否删除
   * @return {*}
   */
  async saveToOSS(filePath: string, dest: any = '/morefun2023/common/upload/', unlink: any = true): Promise<any> {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
      try {
        // 获取文件名称
        const fileName = basename(filePath);
        // 上传至OSS
        const result: Record<string, any> = await this.ossService.put(dest + fileName, filePath);
        // console.log(result);
        //code待验证是否有别的返回值
        if (result?.res?.status == 200) {
          // 删除文件
          if (unlink) fs.unlinkSync(filePath);
          const cdnUrl = result?.url;
          resolve(cdnUrl)
        } else {
          reject({ error: result, msg: 'OSS 文件上传返回值异常' })
        }
      } catch (error) {
        reject({ error, msg: 'OSS 文件上传异常' })
      }
    })
  }
}